package com.example.xunua_weather.fragment;
import android.app.AlertDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;


import com.example.xunua_weather.R;
import com.example.xunua_weather.Sqliteutils.DBManager;
import com.example.xunua_weather.entity.WeatherBean;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import java.util.List;

/**
 * xUtils 网络加载
 */
public class CityWeatherFragment extends BaseFragment implements View.OnClickListener{

    TextView tempTv,cityTv,conditonTv,windTv,tempRangeTv,dateTv,
            clothIndexTv,carIndexTv,ganmaoIndexTv,sportIndexTv,lightIndexTv;
    ImageView dayIv;
    LinearLayout futureLayout;
    String url1 = "http://api.map.baidu.com/telematics/v3/weather?location=";
    String url2 = "&output=json&ak=FkPhtMBK0HTIQNh7gG4cNUttSTyr0nzo";
    private List<WeatherBean.ResultsBean.IndexBean> indexList;
    String location;
    ScrollView outSv;
    private int bgNum;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_city_weather, container, false);
        initView(view);
//        可以通过activity传值获取到当前fragment加载的是哪个地方的天气预报
        Bundle bundle = getArguments();
        location = bundle.getString("city");
        bgNum = bundle.getInt("bg", 2);   // 获取壁纸的编号
        exchangeBg(bgNum);
        String  path = url1+location+url2;
        loadData(path);   //调用父类的获取网络数据的方法
        return view;
    }

    private void exchangeBg(int bgNum) {
//        切换壁纸的方法
        switch (bgNum) {
            case 0:
                outSv.setBackgroundResource(R.mipmap.bg);
                break;
            case 1:
                outSv.setBackgroundResource(R.mipmap.bg2);
                break;
            case 2:
                outSv.setBackgroundResource(R.mipmap.bg3);
                break;
        }
    }

    //  父类定义方法，表示获取网络数据成功时，会调用的方法
    @Override
    public void onSuccess(String s) {
           parseShowData(s);
//           更新原来的数据内容

        int i = DBManager.updateInfoBycity(location, s);
        if (i<=0){
//            更新失败数据库，可能是因为没有这个城市，增加这个城市
            DBManager.addCityInfo(location,s);
        }
    }

//  获取网络数据失败时，会调用的函数
    @Override
    public void onError(Throwable throwable, boolean b) {
//         通过activity传入的地址，到数据库中查找
        String s = DBManager.queryInfoByCity(location);
        if (!TextUtils.isEmpty(s)) {
            parseShowData(s);
        }
    }

    private void parseShowData(String s) {
        /* 将网路请求到的数据解析并展示到View当中*/
        WeatherBean weatherBean = new Gson().fromJson(s, WeatherBean.class);
        WeatherBean.ResultsBean resultsBean = weatherBean.getResults().get(0);
//        获取今天指数列表
        indexList = resultsBean.getIndex();
        dateTv.setText(weatherBean.getDate());
        cityTv.setText(resultsBean.getCurrentCity());
//        获取当天的天气情况
        WeatherBean.ResultsBean.WeatherDataBean todayBean = resultsBean.getWeather_data().get(0);
        windTv.setText(todayBean.getWind());
        tempRangeTv.setText(todayBean.getTemperature());
        conditonTv.setText(todayBean.getWeather());
        String[] split = todayBean.getDate().split("：");
        String todayTemp = split[1].replace(")","");
        tempTv.setText(todayTemp);
        Picasso.with(getActivity()).load(todayBean.getDayPictureUrl()).into(dayIv);

//        向layout当中使用代码添加view的方法   获取四天内的数据
        List<WeatherBean.ResultsBean.WeatherDataBean> futureList = resultsBean.getWeather_data();
//        移除今天的数据
        futureList.remove(0);
        for (int i = 0; i < futureList.size(); i++) {
            View itemView = LayoutInflater.from(getActivity()).inflate(R.layout.item_day_weather,null);
            itemView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            futureLayout.addView(itemView,i);
            TextView idateTv = itemView.findViewById(R.id.item_date_tv);
            TextView iconTv = itemView.findViewById(R.id.item_condition_tv);
            TextView irangeTv = itemView.findViewById(R.id.item_range_tv);
            ImageView iIv = itemView.findViewById(R.id.item_iv);
            WeatherBean.ResultsBean.WeatherDataBean dataBean = futureList.get(i);
            idateTv.setText(dataBean.getDate());
            iconTv.setText(dataBean.getWeather());
            irangeTv.setText(dataBean.getTemperature());
            Picasso.with(getActivity()).load(dataBean.getDayPictureUrl()).into(iIv);

        }
    }

    private void initView(View view) {
        /* 用于初始化控件的函数   */
        outSv = view.findViewById(R.id.frag_sv);
        tempTv = view.findViewById(R.id.frag_city_temp_tv);
        cityTv = view.findViewById(R.id.frag_city_tv);
        conditonTv = view.findViewById(R.id.frag_condition_tv);
        windTv = view.findViewById(R.id.frag_wind_tv);
        tempRangeTv = view.findViewById(R.id.frag_range_tv);
        dateTv = view.findViewById(R.id.frag_time_tv);
        clothIndexTv = view.findViewById(R.id.frag_index_cloth);
        carIndexTv = view.findViewById(R.id.frag_index_car);
        ganmaoIndexTv = view.findViewById(R.id.frag_index_ganmao);
        sportIndexTv = view.findViewById(R.id.frag_index_sport);
        lightIndexTv = view.findViewById(R.id.frag_index_light);
        dayIv = view.findViewById(R.id.frag_condition_iv);
        futureLayout = view.findViewById(R.id.frag_future_layout);
        clothIndexTv.setOnClickListener(this);
        carIndexTv.setOnClickListener(this);
        ganmaoIndexTv.setOnClickListener(this);
        sportIndexTv.setOnClickListener(this);
        lightIndexTv.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        int id = v.getId();
        switch (id) {
            case R.id.frag_index_cloth:
                builder.setTitle("穿衣指数");
                WeatherBean.ResultsBean.IndexBean indexBean = indexList.get(0);
                String msg = indexBean.getZs()+"\n"+indexBean.getDes();
                builder.setMessage(msg);
                builder.setPositiveButton("确定",null);
                break;
            case R.id.frag_index_car:
                builder.setTitle("洗车指数");
                indexBean = indexList.get(1);
                msg = indexBean.getZs()+"\n"+indexBean.getDes();
                builder.setMessage(msg);
                builder.setPositiveButton("确定",null);
                break;
            case R.id.frag_index_ganmao:
                builder.setTitle("感冒指数");
                indexBean = indexList.get(2);
                msg = indexBean.getZs()+"\n"+indexBean.getDes();
                builder.setMessage(msg);
                builder.setPositiveButton("确定",null);
                break;
            case R.id.frag_index_light:
                builder.setTitle("紫外线指数");
                indexBean = indexList.get(4);
                msg = indexBean.getZs()+"\n"+indexBean.getDes();
                builder.setMessage(msg);
                builder.setPositiveButton("确定",null);
                break;
            case R.id.frag_index_sport:
                builder.setTitle("运动指数");
                indexBean = indexList.get(3);
                msg = indexBean.getZs()+"\n"+indexBean.getDes();
                builder.setMessage(msg);
                builder.setPositiveButton("确定",null);
                break;
        }
        builder.create().show();
    }
}
